package cn.itcast.sailing.job;

import cn.itcast.sailing.entity.Task;
import cn.itcast.sailing.entity.TaskLog;
import cn.itcast.sailing.service.TaskLogService;
import cn.itcast.sailing.service.TaskService;
import cn.itcast.sailing.wyy.api.MusicApi;
import cn.itcast.sailing.wyy.domain.entity.MusicUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.ir.annotations.Reference;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
@Component

public class MusicJob implements Job {
    @Autowired
    private  TaskService taskService;
    @Autowired
    private  TaskLogService taskLogService;
    @Autowired
    private  MusicApi api;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        List<Task> list = taskService.list();
        for (Task task : list) {

            MusicUser u = new MusicUser();
            u.setCookie(task.getToken());
            u.setName(task.getName());
            log.info("定时任务入参：{}", JSON.toJSONString(u));
            listenSongsDaily(u);
        }
    }
    public void listenSongsDaily(MusicUser user) {

        //因为每天上限是300首，但是要歌曲不重复，如果需要不重复的300首之后停止，请轮询用户等级信息接口获取听歌量后自行判断，successCount此处只能作为记录请求次数，无法确定是否成功刷歌
        int successCount = 0;
        int nowPlayCount = Integer.parseInt(api.userLevel(user.getCookie()).getJSONObject("data").getString("nowPlayCount"));
        int upperLimit = nowPlayCount + 300;
        log.info("每日听歌打卡=========================");
        //判断是否需要重试
        //首先获取可用的代理ip池
        //获取每日推荐歌单，保证是不影响听歌口味
        JSONObject resourceJSON = api.getRecommentSongs(user.getCookie());
        //解析歌单，返回一个map，key是歌单id,value是歌单中歌曲id的集合
        Map<Long, List<Long>> playListMap = api.parsePlayList(resourceJSON, user.getCookie());
        Set<Long> playListKeySet = playListMap.keySet();
        a:
        for (Long sourceId : playListKeySet) {
            List<Long> songIdList = playListMap.get(sourceId);
            for (Long songId : songIdList) {
                try {
                    JSONObject listenResult = api.listenSong(user.getCookie(), String.valueOf(songId), String.valueOf(sourceId));
                    if (listenResult != null && listenResult.getInteger("code") == 200) {
                        successCount++;
                        log.info(user.getName() + ": 第" + successCount + "首 : " + "====>>歌单id:" + sourceId + "===>>歌曲ID : " + songId + "目标 ：" + upperLimit);
                        TaskLog taskLog = new TaskLog();
                        taskLog.setInfo("第" + successCount + "首 : " + "====>>歌单id:" + sourceId + "===>>歌曲ID : " + songId + "目标 ：" + upperLimit);
                        taskLog.setName(user.getName());
                        taskLog.setCreateTime(new Date());
                        taskLogService.save(taskLog);

                        Thread.sleep(500);
                        //每100首检测一次
                        if (successCount >= 300 && successCount % 50 == 0) {
                            int t = Integer.parseInt(api.userLevel(user.getCookie()).getJSONObject("data").getString("nowPlayCount"));
                            if (t == upperLimit | successCount > 2000) {
                                log.info("已完成每日300首听歌当前等级听歌量为：{}", t);
                                break a;
                            }
                            log.info("当前听歌量为 : {}首,未达到目标 : {}首", t, upperLimit);
                        }
                    }
                } catch (Exception e) {
                    log.info("失败");
                }
            }
        }

    }
}
